package lxs.swift.collector;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;


public class Page<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private final List<T> data;

    private final Long count;

    public Page(List<T> data, Long count) {
        this.data = data;
        this.count = count;
    }

    public Page(List<T> data, Integer count) {
        this.data = data;
        this.count = Long.valueOf(count);
    }

    public static <T> Page<T> empty() {
        return new Page<>(new ArrayList<>(), 0L);
    }

    public static <T> Page<T> paging(Collection<T> collection, Integer page, Integer size) {
        Objects.requireNonNull(collection);
        if (collection.isEmpty()) {
            return empty();
        } else {
            List<T> list = new ArrayList<>(collection);
            List<T> re = new ArrayList<>();
            if (page != null && size != null) {
                if (page <= 0 || size <= 0) {
                    return empty();
                }
                int start = page * size;
                int end = start + size;
                if (start > collection.size()) {
                    return empty();
                }
                if (collection.size() >= end) {
                    re = list.subList(start, end);
                } else {
                    re = list.subList(start, list.size());
                }
            }
            return new Page<>(re, list.size());
        }
    }

    public List<T> getData() {
        return data;
    }

    public Long getCount() {
        return count;
    }

    @Override
    public String toString() {
        return "Page{" + "data=" + data +
                ", count=" + count +
                '}';
    }
}
